package com.ayoka.parenting.ui.live.discussgroup;

import android.app.Activity;
import android.content.DialogInterface;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.view.Gravity;
import android.view.ViewGroup;

import com.ayoka.parenting.R;
import com.ayoka.parenting.bean.BaseResponse;
import com.ayoka.parenting.bean.BasicUserInfoBean;
import com.ayoka.parenting.bean.ChatMessageBean;
import com.ayoka.parenting.bean.DiscussGroupTempRoomBean;
import com.ayoka.parenting.bean.DiscussMember;
import com.ayoka.parenting.bean.UserManager;
import com.ayoka.parenting.interf.RequestCallback;
import com.ayoka.parenting.interf.SimpleRequestCallback;
import com.ayoka.parenting.interf.SimpleTICCallback;
import com.ayoka.parenting.mvp.BasePresenterImpl;
import com.ayoka.parenting.ui.live.ChatDialog;
import com.jincp.common.dialog.DialogDismissListener;
import com.jincp.common.dialog.DialogHelper;
import com.jincp.common.dialog.DialogResultListener;
import com.jincp.common.utils.LiveDataBus;
import com.jincp.common.utils.MyLogger;
import com.jincp.common.utils.UIUtils;
import com.tencent.imsdk.TIMElem;
import com.tencent.imsdk.TIMElemType;
import com.tencent.imsdk.TIMMessage;
import com.tencent.imsdk.TIMTextElem;
import com.tencent.ticsdk.core.TICClassroomOption;
import com.tencent.ticsdk.core.TICManager;
import com.tencent.trtc.TRTCCloudDef;

import java.util.List;

/**
 * @ProjectName: MVPPlugin.
 * @ClassName: DiscussGroupPresenter.
 * @Description: .
 * @Author: jincp.
 * @CreateDate: 2019/10/10 18:17.
 */
public class DiscussGroupPresenter extends BasePresenterImpl<DiscussGroupContract.View> implements DiscussGroupContract.Presenter{

    private DiscussGroupModel model;

     public DiscussGroupPresenter() {
        model = new DiscussGroupModel();
     }

    @Override
    public void getDiscussGroupDetailData(int roomId, String scheduleId) {
        mView.get().showWaitDialog(UIUtils.getString(R.string.loading));
        model.getDiscussGroupDetailData(this, roomId, scheduleId, new SimpleRequestCallback<DiscussGroupTempRoomBean>() {
            @Override
            public void onSuccess(DiscussGroupTempRoomBean data) {
                if (!isAttached()) return;
                mView.get().hideWaitDialog();
                mView.get().configDiscussGroupDetailData(data);
            }

            @Override
            public void onFailure(int errCode, String errMsg) {
                if (!isAttached()) return;
                mView.get().hideWaitDialog();
                mView.get().showToast(errMsg);
                mView.get().configDiscussGroupDetailData(null);
            }
        });
    }

    @Override
    public void joinDiscussGroup(final int roomId) {
        setTRTCCloudParam();
        TICClassroomOption classroomOption = new TICClassroomOption();
        classroomOption.classId = roomId;
        classroomOption.APP_SCENE = TRTCCloudDef.TRTC_APP_SCENE_VIDEOCALL;

        TICManager.getInstance().joinClassroom(classroomOption, new SimpleTICCallback() {
            @Override
            public void onSuccess(Object data) {
                if (!isAttached()) return;
                loadMoreMessage(null);
                mView.get().onJoinDiscussGroupCallback(true);
            }

            @Override
            public void onFailure(int errorCode, String errorMessage) {
                if (!isAttached()) return;
                if (errorCode == 6014) {
                    joinDiscussGroup(roomId);
                } else if (errorCode == 10015) {
//                        mViewRef.get().showToast("课堂不存在:" + roomId + " err:" + errorCode + " msg:" + errorMessage);
                    mView.get().hideWaitDialog();
                    mView.get().onJoinDiscussGroupCallback(false);
                } else {
//                        mViewRef.get().showToast("进入课堂失败:" + roomId + " err:" + errorCode + " msg:" + errorMessage);
                    mView.get().hideWaitDialog();
                    mView.get().onJoinDiscussGroupCallback(false);
                }
            }
        });
    }

    @Override
    public void quitDiscussGroup() {
        TICManager.getInstance().quitClassroom(true, new TICManager.TICCallback() {
            @Override
            public void onSuccess(Object data) {
                MyLogger.d(TAG, "quitClassroom success");
                if (!isAttached()) return;
                mView.get().onQuitDiscussGroupCallback(true);
            }

            @Override
            public void onError(String module, int errCode, String errMsg) {
                MyLogger.d(TAG, "quitClassroom failure" + errMsg);
                if (!isAttached()) return;
                mView.get().onQuitDiscussGroupCallback(false);
            }
        });
    }

    @Override
    public BasicUserInfoBean getMemberByUserId(String userId) {
        BasicUserInfoBean memberByUserId = model.getMemberByUserId(String.valueOf(userId), true);
        return memberByUserId;
    }

    @Override
    public void UpdateMemberSpeakingStatus(int roomId, String userId, boolean enable) {
        RequestCallback callback = new SimpleRequestCallback<BaseResponse>() {
            @Override
            public void onSuccess(BaseResponse data) {
                if (!isAttached()) return;
                mView.get().oUpdateMemberSpeakingStatusCallback(true);
            }

            @Override
            public void onFailure(int errCode, String errMsg) {
                if (!isAttached()) return;
                mView.get().oUpdateMemberSpeakingStatusCallback(false);
            }
        };
        if (enable) {
            model.updateMemberIsSpeaking(this, roomId, userId, callback);
        } else {
            model.updateMemberUnSpeaking(this, roomId, userId, callback);
        }
    }

    @Override
    public void setMemberSpeakingStatus(String userId, boolean enable) {
        BasicUserInfoBean memberByUserId = model.getMemberByUserId(userId, true);
        if (memberByUserId != null) {
            memberByUserId.isSpeaking = enable;
        }
        if (!isAttached()) return;
        mView.get().configOnlineMemberList(model.getMemberList());
    }


    private void loadMoreMessage(TIMMessage message) {
        TICManager.getInstance().getMessageList(20, message, new TICManager.TICCallback<List<TIMMessage>>() {
            @Override
            public void onSuccess(List<TIMMessage> timMessages) {
                formatChatMessageList(timMessages);
            }

            @Override
            public void onError(String module, int errCode, String errMsg) {
                MyLogger.e(TAG, "message error" + errMsg);
            }
        });
    }

    private void formatChatMessageList(List<TIMMessage> messages) {
        if (messages == null || messages.isEmpty()) return;
        for (TIMMessage message : messages) {
            TIMElem element = message.getElement(0);
            if (element.getType() == TIMElemType.Text) {
                TIMTextElem textElem = (TIMTextElem) element;
                BasicUserInfoBean userBean = model.getMemberByUserId(message.getSender(), false);
                if (userBean != null) {
                    ChatMessageBean chatMessageBean = new ChatMessageBean(userBean, textElem.getText(), message);
                    model.saveChatMessage(0, chatMessageBean);
                }
            }
        }
        LiveDataBus.getInstance().with("ChatMessage", String.class).postValue("Load");
    }


    @Override
    public void saveChatMessage(String userId, boolean isChatToSelf, String content, String operation, TIMMessage message) {
        BasicUserInfoBean userBean = model.getMemberByUserId(userId, true);
        ChatMessageBean chatMessageBean = new ChatMessageBean(userBean, content, message);
        chatMessageBean.isChatToSelf = isChatToSelf;
        model.saveChatMessage(chatMessageBean);
        LiveDataBus.getInstance().with("ChatMessage", String.class).postValue(operation);
    }

    @Override
    public void checkOnlineMemberStatus(int subRoomID) {
        mView.get().showWaitDialog(UIUtils.getString(R.string.loading));
        model.checkHasMemberIsSpeaking(this, subRoomID, new SimpleRequestCallback<Integer>() {
            @Override
            public void onSuccess(Integer data) {
                if (!isAttached()) return;
                mView.get().hideWaitDialog();
                mView.get().checkHasMemberIsSpeakingCallback(data);
            }

            @Override
            public void onFailure(int errCode, String errMsg) {
                if (!isAttached()) return;
                mView.get().hideWaitDialog();
                mView.get().showToast(errMsg);
                mView.get().checkHasMemberIsSpeakingCallback(0);
            }
        });
    }

    @Override
    public void showChatMessageDialog(FragmentManager fragmentManager) {
        ChatDialog dialog = new ChatDialog.Builder()
                .setGravity(Gravity.BOTTOM)
                .setSize(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
                .build();
        dialog.setDialogDismissListener(new DialogDismissListener() {
            @Override
            public void dismiss(DialogFragment dialog) {
                if (!isAttached()) return;
                mView.get().onDialogDismiss(dialog);
            }
        });
        dialog.setMessageProvider(new ChatDialog.MessageProvider() {
            @Override
            public List<BasicUserInfoBean> getUserBeanList() {
                return model.getMemberList();
            }

            @Override
            public List<ChatMessageBean> getChatMessageList() {
                return model.getChatMessageList();
            }

            @Override
            public void loadMoreMessage(TIMMessage message) {
                DiscussGroupPresenter.this.loadMoreMessage(message);
            }
        });
        dialog.setDialogResultListener(new DialogResultListener() {
            @Override
            public void result(DialogFragment dialogFragment, Object result) {
                if (!isAttached()) return;
                String[] data = (String[]) result;
                if (data.length > 1) {
                    if (data[0].equals("sendGroupTextMessage")) {
                        DiscussGroupPresenter.this.sendGroupTextMessage(data[1]);
                    } else if (data[0].equals("sendTextMessage")) {
                        DiscussGroupPresenter.this.sendTextMessage(data[1], data[2]);
                    }
                }
            }
        });
        dialog.show(fragmentManager, "ChatDialog");
    }

    @Override
    public void sendTextMessage(final String userId, final String message) {
        TICManager.getInstance().sendTextMessage(userId, message, new TICManager.TICCallback<TIMMessage>() {
            @Override
            public void onSuccess(TIMMessage data) {
                BasicUserInfoBean userBean = model.getMemberByUserId(userId, true);
                ChatMessageBean chatMessageBean = new ChatMessageBean(userBean, "对[" + userId + "]说: " + message, data);
                model.saveChatMessage(chatMessageBean);
                LiveDataBus.getInstance().with("ChatMessage", String.class).postValue("Send");
            }

            @Override
            public void onError(String module, int errCode, String errMsg) {
                if (!isAttached()) return;
                mView.get().showToast("发送消息失败" + errMsg);
            }
        });
    }

    @Override
    public void sendGroupTextMessage(final String message) {
        TICManager.getInstance().sendGroupTextMessage("", message, new TICManager.TICCallback<TIMMessage>() {
            @Override
            public void onSuccess(TIMMessage data) {
                BasicUserInfoBean userBean = model.getMemberByUserId(UserManager.getInstance().uid, true);
                ChatMessageBean chatMessageBean = new ChatMessageBean(userBean, message, data);
                model.saveChatMessage(chatMessageBean);
                LiveDataBus.getInstance().with("ChatMessage", String.class).postValue("Send");
            }

            @Override
            public void onError(String module, int errCode, String errMsg) {
                if (!isAttached()) return;
                mView.get().showToast("发送群消息失败" + errMsg);

            }
        });
    }

    public List<BasicUserInfoBean> formatUserBeanList(List<DiscussMember> userBeanList) {
        if (userBeanList != null && !userBeanList.isEmpty()) {
            for (DiscussMember userBean : userBeanList) {
                model.notifyMember(userBean.UserBasicInfo);
            }
        }
        return model.getMemberList();
    }

    public void setMemberQuit(List<String> userList) {
        for (String userId : userList) {
            BasicUserInfoBean memberByUserId = model.getMemberByUserId(userId, true);
            if (memberByUserId != null) {
                memberByUserId.isOnline = false;
            }
        }
        if (!isAttached()) return;
        mView.get().configOnlineMemberList(model.getMemberList());
    }

    public void setMemberJoin(List<String> userList) {
        for (String userId : userList) {
            BasicUserInfoBean memberByUserId = model.getMemberByUserId(userId, true);
            if (memberByUserId != null) {
                memberByUserId.isOnline = true;
            }
        }
        if (!isAttached()) return;
        mView.get().configOnlineMemberList(model.getMemberList());
    }

    public void showExitDialog(Activity activity, String message) {
        DialogHelper.getOkCancelDialog(activity, "提示", message, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                quitDiscussGroup();
            }
        }).show();
    }

    /**
     * 设置视频通话的视频参数：需要 TRTCSettingDialog 提供的分辨率、帧率和流畅模式等参数
     */
    private void setTRTCCloudParam() {

        // 大画面的编码器参数设置
        // 设置视频编码参数，包括分辨率、帧率、码率等等，这些编码参数来自于 TRTCSettingDialog 的设置
        // 注意（1）：不要在码率很低的情况下设置很高的分辨率，会出现较大的马赛克
        // 注意（2）：不要设置超过25FPS以上的帧率，因为电影才使用24FPS，我们一般推荐15FPS，这样能将更多的码率分配给画质
        TRTCCloudDef.TRTCVideoEncParam encParam = new TRTCCloudDef.TRTCVideoEncParam();
        // 分辨率
        encParam.videoResolution = TRTCCloudDef.TRTC_VIDEO_RESOLUTION_640_360;
        // 分辨率模式（竖屏分辨率）
        encParam.videoResolutionMode = TRTCCloudDef.TRTC_VIDEO_RESOLUTION_MODE_PORTRAIT;
        // 帧率
        encParam.videoFps = 15;
        TICManager.getInstance().getTRTCCloud().setVideoEncoderParam(encParam);

        TRTCCloudDef.TRTCNetworkQosParam qosParam = new TRTCCloudDef.TRTCNetworkQosParam();
        // 服务端控制流量
        qosParam.controlMode = TRTCCloudDef.VIDEO_QOS_CONTROL_SERVER;
        // 优先流畅
        qosParam.preference = TRTCCloudDef.TRTC_VIDEO_QOS_PREFERENCE_SMOOTH;
        TICManager.getInstance().getTRTCCloud().setNetworkQosParam(qosParam);
        // 音量设置100
        TICManager.getInstance().getTRTCCloud().setMicVolumeOnMixing(100);

        TICManager.getInstance().getTRTCCloud().setPriorRemoteVideoStreamType(TRTCCloudDef.TRTC_VIDEO_STREAM_TYPE_SMALL);
        //美颜
        TICManager.getInstance().getTRTCCloud().setBeautyStyle(TRTCCloudDef.TRTC_BEAUTY_STYLE_NATURE, 4, 5, 5);
    }
}
